/** 
 * 创建页面
 */
const fs = require("fs");
const readline = require("readline");
const createHtmlDom = require("htmldom");
const console = require("./public/log")
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

let tempatePath = "./_template/file.html"

const argv = process.argv[2];

if (argv) {
  if (!argv.includes("\/") && !(/\.html$/).test(argv)) {
    console.red("输入的路径有误；请重新输入；例如pages/test/test.html")
    process.exit()
  }
  let argvArr = argv.split(/\//);
  if (!(/\.html$/.test(argvArr[argvArr.length - 1]))) {
    console.red(`输入的路径错误；${argv}必须以.html结尾；例如pages/test.html`)
    process.exit()
  }

  createHomePage(argv)

} else {

  new Promise((resolve, reject) => {
    rl.question("请输入你要创建的目录: 如pages/test/test.html   ", (answer) => {
      resolve(answer)
      rl.close()
    })
  }).then(res => {
    createHomePage(res)
  })

}

// 创建页面
async function createHomePage(path) {
  let pathArr = path.split("\/");

  let dirList = fileArr(pathArr);

  await addDir(dirList); //添加文件

  detailPath(dirList, path)
}

// 处理相对路径
function detailPath(dirList, path) {
  let cloneList = JSON.parse(JSON.stringify(dirList)); //深拷贝

  cloneList.reverse() //反转数组

  if (cloneList.length > 1) {

    let relativePath = "../".repeat(cloneList.length);

    let targetFile = fs.readFileSync(tempatePath, "utf8")

    let $ = createHtmlDom(targetFile)

    replaceRelativePath($("script"), $, "src", relativePath)
    replaceRelativePath($("link"), $, "href", relativePath)

    fs.writeFile(`${path}`, $.html(), "utf-8", (err) => {
      if (err) {
        deleteDir(cloneList)
        return console.red("创建" + path + "失败")
      }

      console.green("创建" + path + "成功")
      process.exit()
    })
  } else {
    fs.copyFile(tempatePath, `${path}`, err => {
      if (err) {
        deleteDir(cloneList)
        return console.red("创建" + path + "失败")
      }
      console.green("创建" + path + "成功")
      process.exit()
    })
  }

}

// 处理script和link相对路径
function replaceRelativePath($dom, sele, attr, targetPath) {
  $dom.each((index, item) => {

    let str = sele(item).attr(attr);

    if (str) {
      let newStr = str.replace(/^(\.\.\/)/, targetPath)
      sele(item).attr(attr, newStr)
    }
  })
}

//删除文件夹
function deleteDir(pathArr) {
  for (let i = pathArr.length - 1; i > 0; i--) {
    let exist = fs.existsSync(item);

    if (exist) {
      fs.rmdirSync(item)
    }
  }
}

//创建文件夹
function addDir(pathArr) {
  return new Promise((resolve, reject) => {
    pathArr.forEach(item => {
      let exist = fs.existsSync(item);

      if (!exist) {
        fs.mkdirSync(item)
      }

    })

    resolve()
  })
}

// 生成文件路径数组
function fileArr(fileList) {
  let arr = fileList.slice(0, fileList.length - 1);

  let dirList = []

  arr.forEach(item => {
    let dir = dirList[dirList.length - 1] ? dirList[dirList.length - 1] + "/" : "";
    dir += item
    dirList.push(dir)
  })

  return dirList
}
